package com.cskaoyan.jdbc.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * @ClassName JdbcUtil
 * @Description: TODO
 * @Author 远志 zhangsong@cskaoyan.onaliyun.com
 * @Date 2023/2/6 16:41
 * @Version V1.0
 **/
public class JdbcUtil {

    public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException {
        Properties properties = new Properties();
        //表示的是Properties会读取硬盘上面的jdbc.properties文件，然后进行自动解析处理
        properties.load(new FileInputStream(new File("jdbc.properties")));
        String username = properties.getProperty("username");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        String driver = properties.getProperty("driver");
        //0.在JDBC中还需要增加一步，引入驱动程序 导包
        //下面这一行代码可以让static静态代码块触发
        Class.forName(driver);
//            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        //1.建立连接（mysql -u root -p）
        //localhost  127.0.0.1永远指的是本机
        //这一行代码其实相当于等价了mysql -u root -p; use mydb4
        return DriverManager.getConnection(url, username, password);
    }

    public static void release(Connection connection, Statement statement, ResultSet resultSet) throws SQLException {
        if(connection != null){
            connection.close();
        }
        if(statement != null){
            statement.close();
        }
        if(resultSet != null){
            resultSet.close();
        }
    }
}
